package com.java.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {
    //登录验证
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //如果访问的是登录页面
        if (request.getRequestURI().contains("login.html")) {
            return true;
        } else {
            //没有登录
            if (request.getSession().getAttribute("user") == null) {
                //请求登录
                if (request.getRequestURI().contains("login")) {
                    //通过
                    return true;
                }
                if (request.getRequestURI().contains("loginOut")) {
                    //通过
                    return true;
                }
                //若不是请求登录，则注解跳转到登录页面
                response.sendRedirect("http://localhost/login.html");
            } else {
                //已经登录
                return true;
            }
        }
        return false;
    }
}